package com.vito.demo.hibernate.demo1;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import java.util.Properties;

/**
 * Created by lingzhiyuan.
 * Date : 16/3/31.
 * Time : 下午7:42.
 * Description:
 */
public class Start {

    public static void main(String[] args) {
        Configuration configuration = new Configuration();
        Properties properties = new Properties();
        properties.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
        properties.put("hhibernate.ibernate.connection.url",
                       "jdbc:mysql://localhost:3306/test?characterEncoding=utf8");
        properties.put("hibernate.connection.username", "vito");
        properties.put("hibernate.connection.password", "lzy371148667");

        properties.put("hibernate.show_sql", "true");
        properties.put("hibernate.dialect", "org.hibernate.dialect" +
                                            ".MySQL5InnoDBDialect");

        //连接池配置，生产环境必须用c3p0

        //初始化时获取三个连接，取值应在minPoolSize与maxPoolSize之间。Default: 3
        properties.put("hibernate.c3p0.min_size", "1");
        //连接池中保留的最大连接数。Default: 15
        properties.put("hibernate.c3p0.max_size", "20"); //最大连接数
        //当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 5
        properties.put("hibernate.c3p0.acquire_increment", "2");
        //每60秒检查所有连接池中的空闲连接。Default: 0
        properties.put("hibernate.c3p0.idle_test_period", "200");

        //JDBC的标准参数，用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements
        //属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
        //如果maxStatements与maxStatementsPerConnection均为0，则缓存被关闭。Default: 0
        properties.put("hibernate.c3p0.max_statements", "100");

        //最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0
        properties.put("hibernate.c3p0.timeout", "1000");
        properties.put("hibernate.c3p0.validate", "true");

        properties.put("hibernate.hbm2ddl.auto", "update");
        configuration.setProperties(properties);
        configuration.addAnnotatedClass(NewsEntity.class);
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(properties).build();
        SessionFactory sessionFactory = configuration.buildSessionFactory
                (serviceRegistry);
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        NewsEntity newsEntity = new NewsEntity();
        newsEntity.setTitle("Hello");
        newsEntity.setContent("from java");

        session.save(newsEntity);
        transaction.commit();
        session.close();
        sessionFactory.close();
    }

}
